<script setup name="ZlPrompt">
import { Delete } from '@element-plus/icons-vue'
import Message from 'vue-m-message'
import { reactive } from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import zlPromptService from '@/api/finance/zlPrompt.js'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useDict } from '@/utils/dict.js'
import BaseForm from '@/components/BaseForm/BaseForm.vue'

const promptId = ref('')
const activeName = ref('first')
const tableData = ref([])
const customerName = ref([])
const queryParam = ref({})
const ids = ref([])
const limit = ref(1)
const fileList = ref([])
const applyVisible = ref(false)
const scVisible = ref(false)
const btnLoad = ref(false)
const updateDialogVisible = ref(false)
const updateDialogTitle = ref('')
const customerlist = ref([])
const formDisabled = ref(false)
const { proxy } = getCurrentInstance()
const {
  sys_proceeds_time,
  sys_pay_status,
  sys_patent_type,
  zl_prompt_status,
  invoice_type,
} = useDict(
  'sys_proceeds_time',
  'sys_pay_status',
  'sys_patent_type',
  'zl_prompt_status',
  'invoice_type',
)

const searchConfig = reactive([
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerlist,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
  },
])

const tableColumns = reactive([
  { type: 'checkbox', width: 50 },

  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 220,
    showOverflow: 'tooltip',
  },
  {
    field: 'dsMoney',
    title: '待收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'shMoney',
    title: '代理费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'syMoney',
    title: '官费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'otherMoney',
    title: '其他费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'status',
    title: '状态',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
    slots: { default: 'status' },
  },
  {
    field: 'operate',
    title: '操作',
    headerAlign: 'center',
    align: 'center',
    minWidth: 200,
    fixed: 'right',
    slots: { default: 'operate' },
  },
])
// 查看开票
const zlPromptUploadList = ref({})
const applyFormList = ref({})
// 文件id
const invoiceFileId = ref('')
// 申请开票
const applyList = ref([
  {
    field: 'invoiceType',
    label: '票种',
    type: 'select',
    options: {
      data: invoice_type,
      label: 'label',
      value: 'value',
      key: 'value',
    },
    rules: [{ required: true, message: '请输入票种', trigger: 'change' }],
  },
  {
    field: 'invoicingMoney',
    label: '开票金额',
    type: 'custom',
    slotName: 'invoicingMoney',
    rules: [{ required: true, message: '请输入开票金额', trigger: 'change' }],
  },
  {
    field: 'buyerHeader',
    label: '购方抬头',
    type: 'input',
    rules: [{ required: true, message: '请输入购方抬头', trigger: 'change' }],
  },
  {
    field: 'buyerNumber',
    label: '购方纳税人识别号',
    type: 'input',
    rules: [
      { required: true, message: '请输入购方纳税人识别号', trigger: 'change' },
    ],
  },
  {
    field: 'buyerAddress',
    label: '购方地址',
    type: 'input',
  },
  {
    field: 'buyerPhone',
    label: '购方电话',
    type: 'input',
  },
  {
    field: 'buyerBank',
    label: '购方开户行',
    type: 'input',
  },
  {
    field: 'buyerAccount',
    label: '购方账户',
    type: 'input',
  },
  {
    field: 'customerName',
    label: '开票单位',
    type: 'custom',
    slotName: 'customerName',
    rules: [
      { required: true, message: '请输入购方纳税人识别号', trigger: 'change' },
    ],
  },
  {
    field: 'remark',
    label: '开票备注',
    type: 'textarea',
    span: 24,
  },
])
const applyFormModel = ref({})
// 上传
const scList = ref([
  {
    field: 'invoiceNumber',
    label: '发票号码',
    type: 'input',
    rules: [{ required: true, message: '请输入发票号码', trigger: 'change' }],
  },
  {
    field: 'invoicingDate',
    label: '开票日期',
    type: 'date',
    slotName: 'invoicingDate',
    span: 12,
  },
  {
    field: 'invoicingMoney',
    label: '开票金额',
    type: 'input',
  },
  {
    field: 'invoicingSubject',
    label: '开票主体',
    type: 'input',
  },
  {
    field: 'remark',
    label: '开票备注',
    type: 'textarea',
    span: 24,
  },
  {
    field: 'invoiceFileId',
    label: '发票',
    type: 'custom',
    slotName: 'invoiceFileId',
    span: 24,
  },
])
const scFormModel = ref({})
const updateFormList = ref([
  { type: 'seq', align: 'center', width: 50 },

  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'contractNo',
    title: '合同编号',
    align: 'center',
    minWidth: 150,
    showOverflow: 'tooltip',
  },
  {
    field: 'reelNumber',
    title: '案件编号',
    align: 'center',
    minWidth: 140,
    showOverflow: 'tooltip',
  },
  {
    field: 'patentName',
    title: '案件名称',
    align: 'center',
    minWidth: 140,
    showOverflow: 'tooltip',
  },
  {
    field: 'businessName',
    title: '业务类型',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'skNode',
    title: '收款节点',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
    slots: { default: 'skNode' },
  },
  {
    field: 'dsMoney',
    title: '待收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'dlMoney',
    title: '代理费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'gfMoney',
    title: '官费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'otherMoney',
    title: '其他费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
])
const tableData1 = ref({})
const tabsList = reactive([
  {
    label: '明细信息',
    name: 'first',
    icon: 'tab-first',
    id: 1,
  },
  {
    label: '开票申请',
    name: 'second',
    icon: 'kaipiao-first',
    id: 2,
  },
  {
    label: '发票信息',
    name: 'third',
    icon: 'fapiao-first',
    id: 3,
  },
])
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const pagerConfig1 = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

onMounted(() => {
  getList()
})

function getList() {
  const formData = {
    ...queryParam.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
  }
  btnLoad.value = true
  zlPromptService.list(formData).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    btnLoad.value = false
  })
  zlPromptService.optionList().then((res) => {
    customerlist.value = res.data
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange({ checked, records, reserves }) {
  const res = records.map(item => item.zlpromptId)
  if (reserves.length > 0) {
    if (checked) {
      ids.value.push(...res)
    }
    else {
      const customerIdSet = new Set(reserves.map(item => item.zlpromptId))
      ids.value = ids.value.filter(item => customerIdSet.has(item))
    }
  }
  else {
    ids.value = res
  }
}

function handleSearch(e, type) {
  if (type === 'reset') {
    customerName.value = []
  }
  queryParam.value = {
    locationArea: customerName.value.join('/'),
    registerDateMin: e.registDate
      ? `${formatDate(e.registDate[0], 'YYYY-MM-DD')}`
      : null,
    registerDateMax: e.registDate
      ? `${formatDate(e.registDate[1], 'YYYY-MM-DD')}`
      : null,
    ...e,
  }
  delete queryParam.value.registDate
  getList()
}

// function handleUpdateSubmit() {
//   console.log(
//     updateFormModel.value.remark,
//     "remark",
//     updateFormModel.value.zlagencyId
//   );
//   if (updateFormModel.value.remark && updateFormModel.value.zlagencyId) {
//     zlPromptService
//       .update(updateFormModel.value)
//       .then((response) => {
//         console.log("修改成功");
//         Message.success("修改成功");
//         updateDialogVisible.value = false;
//         getList();
//       })
//       .finally(() => {});
//   } else {
//     console.log("修改失败");
//     updateDialogVisible.value = false;
//   }
// }

function handleReset() {
  console.log('1212')
  updateDialogVisible.value = false
  scVisible.value = false
  applyVisible.value = false
}

function handleDelete(row) {
  console.log(row, ids.value, 'id')
  const patentIds = row || ids.value
  console.log(patentIds, 'patentIds')
  zlPromptService.delete(patentIds).then((res) => {
    const { code } = res
    if (code === 200) {
      Message.success('删除成功')
      getList()
    }
  })
}

// 查看
function handleFormAction(row, type) {
  activeName.value = 'first'
  formDisabled.value = true
  applyFormList.value = {}
  zlPromptUploadList.value = {}
  updateDialogTitle.value = '查看'
  const id = row.zlpromptId
  // promptId.value=row.promptId
  zlPromptService
    .getDetail(id)
    .then((response) => {
      //   updateFormModel.value.zlpromptId = response.data.zlpromptId;
      //   updateFormModel.value.remark = response.data.remark;
      tableData1.value = response.data.sysZlAgencyVos
      // tableData1.value = response.data.sysZlAgencyVos;
      pagerConfig1.value.total = response.data.sysZlAgencyVos.length
      tableData1.value.map((item) => {
        return item.customerName = response.data.customerName
      })
      console.log(tableData1.value, 'tableData1.value')
      updateDialogVisible.value = true
    })
    .catch((err) => {})
  zlPromptService.getApply(id).then((res) => {
    if (res.data) {
      applyFormList.value = res.data
    }
  })
  zlPromptService.getzlPromptUpload(id).then((res) => {
    if (res.data) {
      zlPromptUploadList.value = res.data
    }
  })
}

function handleExport() {
  proxy.download(
    'system/customerInformation/export',
    { ...queryParam.value, exportIds: ids.value.join(',') },
    `user_${new Date().getTime()}.xlsx`,
  )
}

// 申请开票
function handleApply(row) {
  applyFormModel.value = []
  applyVisible.value = true
  updateDialogTitle.value = '申请开票'
  applyFormModel.value.invoicingMoney = row.dsMoney
  applyFormModel.value.customerName = row.customerName
  applyFormModel.value.customerId = row.customerId
  applyFormModel.value.promptId = row.zlpromptId
}
// 提交开票
function applySubmit() {
  zlPromptService.addApply(applyFormModel.value).then((res) => {
    if (res.code == '200') {
      Message.success('开票成功')
      applyVisible.value = false
      getList()
    }
  })
}
// 上传
function handlesc(row) {
  updateDialogTitle.value = '上传发票'
  scFormModel.value = []
  scVisible.value = true
  scFormModel.value.promptId = row.zlpromptId
}
function scSubmit() {
  zlPromptService.zlPromptUpload(scFormModel.value).then((res) => {
    if (res.code === '200') {
      Message.success('上传成功')
      scVisible.value = false
      getList()
    }
  })
}
function handleActiveName(name) {
  activeName.value = name
  lc.value = !lc.value
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <SearchBar :search-config="searchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never">
      <div class="toolbar flex mb-1">
        <div class="mb-2 space-x-3">
          <el-button
            v-hasPermi="['system:finance:zlPrompt:remove']"
            type="danger"
            class="el-gradient-danger"
            :disabled="ids.length === 0"
            @click="handleDelete(null)"
          >
            删除
            <el-icon class="el-icon--right">
              <Delete />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:zlPrompt:export']"
            type="warning"
            class="el-gradient-warning"
            @click="handleExport()"
          >
            导出
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
        </div>
        <RightToolbar />
      </div>
      <vxe-grid
        :data="tableData"
        :row-config="{
          keyField: 'zlpromptId',
        }"
        :columns="tableColumns"
        :pager-config="pagerConfig"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellClass"
        :loading="btnLoad"
        max-height="630px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #skNode="{ row }">
          <dict-tag :options="sys_proceeds_time" :value="row.skNode" />
        </template>

        <template #status="{ row }">
          <dict-tag :options="zl_prompt_status" :value="row.status" />
        </template>
        <template #operate="{ row }">
          <el-button
            v-hasPermi="['system:finance:zlPrompt:query']"
            text
            type="success"
            size="small"
            @click="handleFormAction(row, 'view')"
          >
            查看
          </el-button>

          <span
            v-if="row.status === 0"
            v-hasPermi="['system:finance:zlPrompt:remove']"
          >
            <el-popconfirm
              title="确认删除吗？"
              width="200px"
              @confirm="handleDelete(row.zlpromptId)"
            >
              <template #reference>
                <el-button text size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
          <el-button
            v-if="row.status === '1'"
            v-hasPermi="['system:zlPromptApply:add']"
            size="small"
            text
            type="primary"
            @click="handleApply(row)"
          >
            申请开票
          </el-button>
          <span v-if="row.status === '2'">
            <el-button
              v-hasPermi="['system:zlPromptUpload:add']"
              size="small"
              text
              type="success"
              @click="handlesc(row)"
            >上传</el-button>
          </span>
        </template>
      </vxe-grid>
    </el-card>
    <!-- 查看 -->
    <el-drawer
      v-model="updateDialogVisible"
      :destroy-on-close="true"
      class="custom-drawer"
      size="60%"
      :disabled="formDisabled"
      @close="handleReset"
      :show-close="false"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <div class="content-tabs mb-5">
        <ul class="flex">
          <li
            v-for="item in tabsList"
            :key="item.id"
            class="flex-1 text-center rounded h-13 flex-center text-[16px] tabs-item"
            :class="{ active: activeName === item.name }"
            @click="handleActiveName(item.name)"
          >
            <span>
              <SvgIcon
                :name="item.icon"
                class="tabs-icon"
                class-name="mr-1 w-[21px] h-[21px] relative top-[1px]"
              />
            </span>
            {{ item.label }}
          </li>
        </ul>
      </div>

      <div v-if="activeName === 'first'">
        <!-- <template #label>
            <span class="custom-tabs-label">
              <el-icon style="vertical-align: text-bottom; margin-right: 5px"
                ><MessageBox
              /></el-icon>
              <span>明细信息</span>
            </span>
          </template> -->
        <vxe-grid
          :data="tableData1"
          :columns="updateFormList"
          :pager-config="pagerConfig1"
          :column-config="{ resizable: true }"
          header-cell-class-name="headerCellContractClass"
          :loading="btnLoad"
          border
          @page-change="handlePageChange"
          @checkbox-all="handleCheckChange"
          @checkbox-change="handleCheckChange"
        >
          <template #skNode="{ row }">
            <dict-tag :options="sys_proceeds_time" :value="row.skNode" />
          </template>
        </vxe-grid>
      </div>
      <div v-if="activeName === 'second'">
        <!-- <template #label>
            <span class="custom-tabs-label">
              <el-icon style="vertical-align: text-bottom; margin-right: 5px"
                ><Connection
              /></el-icon>
              <span>开票申请信息</span>
            </span>
          </template> -->
        <BaseForm
          :is_button="no"
          :field-list="applyList"
          :model="applyFormList"
          class="px-5"
          disabled
          :options="{ labelWidth: '140px' }"
          @submit="applySubmit"
          @cancel="handleReset"
        >
          <template #invoicingMoney>
            <el-input
              v-model="applyFormList.invoicingMoney"
              disabled
              placeholder="请输入开票金额"
            />
          </template>
          <template #customerName>
            <el-input
              v-model="applyFormList.customerName"
              disabled
              placeholder="请输入开票单位"
            />
          </template>
        </BaseForm>
      </div>
      <div v-if="activeName === 'third'">
        <!-- <template #label>
            <span class="custom-tabs-label">
              <el-icon style="vertical-align: text-bottom; margin-right: 5px"
                ><Paperclip
              /></el-icon>
              <span>发票信息</span>
            </span>
          </template> -->
        <BaseForm
          :is_button="no"
          :field-list="scList"
          :model="zlPromptUploadList"
          class="px-5"
          disabled
          @submit="scSubmit"
          @cancel="handleReset"
        >
          <template #invoiceFileId>
            <file-upload
              v-model="zlPromptUploadList.invoiceFileId"
              :limit="limit"
            />
          </template>
        </BaseForm>
      </div>
      <div class="close-btn flex-center" @click="handleReset">
        <el-icon>
          <CloseBold />
        </el-icon>
      </div>
    </el-drawer>
    <!-- 申请开票 -->
    <el-dialog
      v-model="applyVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      width="50%"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="applyList"
        :model="applyFormModel"
        class="px-5"
        :options="{ labelWidth: '140px' }"
        @submit="applySubmit"
        @cancel="handleReset"
      >
        <template #invoicingMoney>
          <el-input
            v-model="applyFormModel.invoicingMoney"
            disabled
            placeholder="请输入开票金额"
          />
        </template>
        <template #customerName>
          <el-input
            v-model="applyFormModel.customerName"
            disabled
            placeholder="请输入开票单位"
          />
        </template>
      </BaseForm>
    </el-dialog>

    <!-- 上传发票 -->
    <el-dialog
      v-model="scVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      width="50%"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="scList"
        :model="scFormModel"
        class="px-5"
        @submit="scSubmit"
        @cancel="handleReset"
      >
        <template #invoiceFileId>
          <file-upload
            v-model="scFormModel.invoiceFileId"
            :limit="limit"
          />
        </template>
      </BaseForm>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.dialog-header {
  width: 180px;
  height: 0;
  border-width: 0px 45px 45px 0px;
  border-style: none solid solid;
  border-color: transparent transparent var(--el-color-primary);
  color: #fff;
  display: flex;
  justify-content: center;
}
::v-deep(.el-tabs__nav) {
  width: 100% !important;

  .el-tabs__item {
    width: 33%;
  }
}
.tabs-item {
  background: var(--el-bg-color-page);
  color: #999;
  transition: all 0.3s;
  cursor: pointer;
  &:hover {
    background: #e8f2ff;
    color: var(--el-color-primary);
    transition: all 0.3s;
  }
}
.tabs-item.active {
  background: #e8f2ff;
  color: var(--el-color-primary);
  transition: all 0.3s;
  font-weight: bold;
  .tabs-icon {
    color: var(--el-color-primary);
    width: 20px;
    height: 20px;
  }
}
.close-btn {
  position: fixed;
  top: 50%;
  margin-left: -65px;
  cursor: pointer;
  border: none;
  outline: none;
  width: 45px;
  height: 45px;
  font-size: 22px;
  line-height: 40px;
  text-align: center;
  background-color: var(--el-color-primary);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);

  &:hover {
    background-color: #f56c6c;

    i {
      transition: transform 0.5s, -webkit-transform 0.5s;
      transform: rotate(90deg);
    }
  }
}
</style>
